/**
 * 
 */
package com.ez.supervise.model.dto;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.ez.supervise.model.sys.Permission;
import com.ez.supervise.util.FreemarkerUtil;

/**
 * @author searph.wang
 * @email searph.wang@gmail.com
 * @Created at 2009-11-4
 * 
 */
public class MainMenu {
    private String key;
    private Permission permission;
    private Map<String, Permission> subMenus = new LinkedHashMap<String, Permission>();

    public MainMenu() {
    }
    
    public MainMenu(Permission permission) {
	this.permission = permission;
	if(permission != null){
	    key = permission.getResId();
	}
    }
    public void addSub(List<Permission> permissionList) {
	for (Permission permission : permissionList) {
	    if (permission != null) {
		subMenus.put(permission.getResId(), permission);
	    }
	}
    }
    
    public String toScript(){
	StringBuilder sb = new StringBuilder(512);
	String  result;
	Map map = new HashMap();
	FreemarkerUtil.putTemplate(Menu.MAIN_MENU_TEMPLATE);
	FreemarkerUtil.putTemplate(Menu.SUB_MENU_TEMPLATE);
	//set main menu
	map.put(Menu.KEY_MENU, permission);
	result = FreemarkerUtil.processTemplate(Menu.MAIN_MENU_TEMPLATE,map);
	sb.append(result);
	//set sub
	for (Iterator iterator = subMenus.values().iterator(); iterator.hasNext();) {
	    Permission sub = (Permission) iterator.next();
	    map.put(Menu.KEY_MENU, sub);
	    result = FreemarkerUtil.processTemplate(Menu.SUB_MENU_TEMPLATE, map);
	    String temp = sb.toString();
	    int pos =  temp.lastIndexOf(Menu.ITEMS_EMPTY) + Menu.ITEMS_EMPTY.length() - 1;
	    sb.insert(pos, result);
	}
	result = sb.toString();
	result = StringUtils.remove(result, "," + Menu.ITEMS_EMPTY);
	return result;
    }
    
    
    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public Permission getPermission() {
        return permission;
    }

    public void setPermission(Permission permission) {
        this.permission = permission;
    }

    public Map<String, Permission> getSubMenus() {
        return subMenus;
    }

    public void setSubMenus(Map<String, Permission> subMenus) {
        this.subMenus = subMenus;
    }

}
